<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(obj, ind) in suggestions"
      :key="ind"
      @click="$emit('search', obj)"
    >
      <!-- <div slot="title"></div> -->
      <div slot="title" v-html="hightLight(obj)"></div>
    </van-cell>

    <!-- <van-cell title="黑马程序员..." icon="search"></van-cell>
    <van-cell title="黑马程序员..." icon="search"></van-cell>
    <van-cell title="黑马程序员..." icon="search"></van-cell>
    <van-cell title="黑马程序员..." icon="search"></van-cell> -->
  </div>
</template>

<script>
import { getSuggestion } from '../../../api/search';
import { debounce } from 'lodash';
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      suggestions: [],
      htmlStr: 'Hello <span style="color: red">World</span>'
    };
  },
  computed: {},
  watch: {
    searchText: {
      // 当searchText发生改变时候就会调用handler函数
      handler: debounce(function (v) {
        // console.log(v);
        this.loadSuggestions(v);
      }, 2000),
      // async handler(v) {
      //   // console.log(v);
      //   this.loadSuggestions(v);
      // },
      immediate: true
    }
  },
  created () {},
  mounted () {},
  methods: {
    async loadSuggestions (v) {
      try {
        const { data } = await getSuggestion(v);
        // console.log(data);
        this.suggestions = data.data.options;
      } catch (error) {
        this.$toast('数据获取失败，请稍后重试');
      }
    },
    hightLight (str) {
      const hightLightStr = `<span style="color:#3296fa">${this.searchText}</span>`;
      const reg = new RegExp(this.searchText, 'gi');
      return str.replace(reg, hightLightStr);
    }
  }
};
</script>

<style scoped lang="less"></style>
